/**
 * @author 李桥
 * @date 2018/12/6
 * @Description: 封装键盘事件的处理
 */

/**
 * 单例模式设计KeyEvent
 * @type {null}
 */
var uniqueInstance = null;

class KeyEvent {
    /**
     * @param cfg 配置参数，可以配置keydown或者keyup监听函数，不配置使用下面的默认配置
     */
    constructor(cfg){
        var self = this;
        this.KeyDownMap = Object.assign({
            KEY_CTRL:false,
            KEY_SHIFT:false,
            KEY_ALT:false,
            KEY_S:false,
            KEY_W:false
        },cfg.KeyDownMap);

        this.keyEventListeners = Object.assign({
            keyDownListener:function (e) {
                if(e.keyCode == 17){
                    self.KeyDownMap.KEY_CTRL = true;
                }
                if(e.keyCode == 16){
                    self.KeyDownMap.KEY_SHIFT = true;
                }
            },
            keyUpListener:function (e) {
                if(e.keyCode == 17){
                    self.KeyDownMap.KEY_CTRL = false;
                }
                if(e.keyCode == 16){
                    self.KeyDownMap.KEY_SHIFT = false;
                }
            }
            //其它配置，扩展准备
        },cfg.keyEventListeners);

        this.initKeyDownHandler();
    }

    initKeyDownHandler(){
        document.addEventListener("keydown",this.keyEventListeners.keyDownListener);
        document.addEventListener("keyup",this.keyEventListeners.keyUpListener);
    }

    static getInstance(cfg){
        if(uniqueInstance === null){
            uniqueInstance = new KeyEvent(cfg);
        }
        return uniqueInstance;
    }
}
export default KeyEvent;
